package org.jprogger.myworld.api.request;

import java.util.Map;


/**
 * 
 * @author jprogger
 *
 */
public class ApiRequestFactory {

	public static ApiRequest createApiRequest(String url, Map<String, Object> params) {
		
		if (params.isEmpty() || params == null)
			throw new IllegalArgumentException("Request parameters can't be empty or null");
				
		ApiRequestParams requestData = new ApiRequestParamsImpl(params);
		ApiRequest apiRequest = new ApiRequestImpl(requestData);
		apiRequest.setApiRequestUrl(url);
		apiRequest.setRequestFormat((String)params.get("format"));
		return apiRequest;
	}
	
	/**
	 *  hiding constructor
	 */
	private ApiRequestFactory() {}
	
	/**
	 * 
	 * @author jprogger
	 * 
	 * Implementation of {@link ApiRequestParams} interface
	 */
	private static class ApiRequestParamsImpl implements ApiRequestParams {
		
		private Map<String, Object> params;
		
		ApiRequestParamsImpl(Map<String, Object> params) {
			this.params = params;
		}

		@Override
		public Map<String, Object> getParameterMap() {
			return params;
		}

		@Override
		public void setParameterMap(Map<String, Object> params) {
			this.params = params;
		}

	}
	
	/**
	 * 
	 * @author jprogger
	 * 
	 * Implementation of {@link ApiRequest} interface
	 */
	private static class ApiRequestImpl implements ApiRequest {

		private String url;
		private String format;
		private ApiRequestParams requestData;
			
		ApiRequestImpl(ApiRequestParams data) {
			this.requestData = data;
		}
		
		@Override
		public String getApiRequestUrl() {
			return url;
		}
		
		@Override
		public void setApiRequestUrl(String url) {
			this.url = url;
		}
		
		@Override
		public boolean isRequestSigned() {
			
			boolean signed = false;
			if (requestData != null) {
				String sign = (String)requestData.getParameterMap().get("sig");
				if (sign != null) signed = true;
			}
			return signed;
		}
		
		@Override
		public String getSignature() {
			String sign = null;
			if(requestData != null) {
				sign = (String)requestData.getParameterMap().get("sig");
			} 
			return sign;
		}
		
		@Override
		public String getRequestFormat() {
			return format;
		}
		
		@Override
		public void setRequestFormat(String format) {
			this.format = format;
		}
		
		@Override
		public void setSignature(String signature) {
			if (requestData != null) {
				requestData.getParameterMap().put("sig", signature);
			}
		}
		
		@Override
		public ApiRequestParams getApiRequestParams() {
			return requestData;
		}

		@Override
		public void setApiRequestParams(ApiRequestParams apiRequestData) {
			this.requestData = apiRequestData;
		}


	}
}
